package com.project.aaos;

import com.project.aaos.config.Config;
import com.project.aaos.config.ConfigUtil;
import com.project.aaos.controller.HomeController;
import com.project.aaos.dao.Studentmapper;
import com.project.aaos.exception.AAOSException;
import com.project.aaos.job.BusinessJob;
import com.project.aaos.job.InDbJob;
import com.project.aaos.pojo.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;
import org.quartz.*;
import org.quartz.impl.StdScheduler;
import org.quartz.impl.StdSchedulerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Properties;

public class Start {


    private  Logger log = Logger.getLogger(Start.class);

    public static void main(String[] args) throws IOException {

        Start start = new Start();
        start.startup();

    }

    public void startup(){

        log.info("[ AAOS ]******************AAOS STARTUP*****************");
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("system.properties");
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            log.info("aaos",e);
        }
        String values = properties.getProperty("com.aaos.orgcodes");
        String[] orgCodes = values.split(",");

        for (String orgCode:orgCodes){
            startupDetail(orgCode);
            try {

            } catch (Exception e) {
                throw new AAOSException(e.getMessage());
            }
        }
    }

    public void startupDetail(String orgCode) {

        Config config = ConfigUtil.loadConfig(orgCode);

        SqlSession session = null;
        try {
            session = generateSession(config);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //runDbJob(config,session);
        runBusinessJob(config,session);




    }

    private void runDbJob(Config config,SqlSession session){

        JobDetail job = JobBuilder.newJob(BusinessJob.class).build();
        job.getJobDataMap().put("session",session);
        job.getJobDataMap().put("config",config);


        SimpleScheduleBuilder ssb = SimpleScheduleBuilder.simpleSchedule();
        ssb.withIntervalInSeconds(Integer.parseInt(config.getIndbInterval())*60);
        ssb.repeatForever();
        Trigger trigger = TriggerBuilder.newTrigger().withSchedule(ssb).build();
        Scheduler inDbScheduler = null;
        try {
            inDbScheduler = new StdSchedulerFactory().getScheduler();
            inDbScheduler.scheduleJob(job,trigger);
            inDbScheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

    }

    private void runBusinessJob(Config config,SqlSession session){

        JobDetail job = JobBuilder.newJob(BusinessJob.class).build();
        job.getJobDataMap().put("session",session);
        job.getJobDataMap().put("config",config);


        SimpleScheduleBuilder ssb = SimpleScheduleBuilder.simpleSchedule();
        ssb.withIntervalInSeconds(Integer.parseInt(config.getIndbInterval())*60);
        ssb.repeatForever();
        Trigger trigger = TriggerBuilder.newTrigger().withSchedule(ssb).build();
        Scheduler inDbScheduler = null;
        try {
            inDbScheduler = new StdSchedulerFactory().getScheduler();
            inDbScheduler.scheduleJob(job,trigger);
            inDbScheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

    }

    public SqlSession generateSession(Config config) throws IOException {

        Reader reader = Resources.getResourceAsReader(config.getDbName());
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession session = sessionFactory.openSession(true);
        return session;
    }

/*    public static void main(String[] args) throws Exception {

        System.out.println("你好");

        Class.forName(name);// 指定连接类型
        Connection conn = DriverManager.getConnection(url, user, password);// 获取连接
        PreparedStatement pst = conn.prepareStatement("select * from student");// 准备执行语句
        ResultSet resultSet = pst.executeQuery();
        while (resultSet.next()){
            String address = resultSet.getString("address");
            System.out.println(address);
        }
        resultSet.close();
        conn.close();
    }*/


    /*public static void main(String[] args) {

        SqlSession session = null;
        try {
            String resource = "conf1.xml";
            InputStream is = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            session = sqlSessionFactory.openSession();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Studentmapper studentmapper = session.getMapper(Studentmapper.class);
        List<Student> list = studentmapper.getObjects();
        for (Student student:list){
            System.out.println(student);
        }


        SqlSession session1 = null;
        try {
            String resource = "conf2.xml";
            InputStream is = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            session1 = sqlSessionFactory.openSession();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Studentmapper studentmapper1 = session1.getMapper(Studentmapper.class);
        List<Student> list1 = studentmapper1.getObjects();
        for (Student student:list1){
            System.out.println(student);
        }
    }*/

}
